package com.note.feng.juc.mutithread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 库存超卖，单体应用纯Java实现
 * @author yuhf
 */
public class AtomicDemo {
    public static void main(String[] args) {
        int k = 100000;
        AtomicInteger stock = new AtomicInteger(k);
        ExecutorService executor = Executors.newFixedThreadPool(10);
        long start = System.currentTimeMillis();
        for(int i = 0; i < k; i ++){
            executor.execute(() -> {
                if(stock.get() == 0){
                    System.out.println("stock is 0");
                }else{
                    stock.decrementAndGet();
                }
//                try {
//                    Thread.sleep(1000L);
//                } catch (InterruptedException e) {
//                    throw new RuntimeException(e);
//                }
            });
        }
        executor.shutdown();
        System.out.println("K:" + k);
//        long end = System.currentTimeMillis();
//        System.out.println("1:" + (end - start));
//        for(int i = 0; i < k; i ++){
//            try {
//                Thread.sleep(10L);
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//        }
//        System.out.println(System.currentTimeMillis() - end);
    }
}
